//
//  NearMapViewController.m
//  Travelmemory
//
//  Created by lanou3g on 16/3/31.
//  Copyright © 2016年 ABCD. All rights reserved.
//

#import "NearMapViewController.h"
#import <MAMapKit/MAMapKit.h>
#import <MapKit/MapKit.h>
#import "TraveHeader.h"

@interface NearMapViewController ()<MAMapViewDelegate, UIActionSheetDelegate>

{
    // 用户经纬度变量
    CLLocation *_currentLocation;
    
}

@property (nonatomic, strong) NSMutableArray *availableMaps;
@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic, strong) MAPointAnnotation *annotation;//大头针
@property (nonatomic, strong) NSMutableArray *annotationArray;// 大头针数组

@end

@implementation NearMapViewController

- (NSMutableArray *)availableMaps {
    if (!_availableMaps) {
        _availableMaps = [NSMutableArray array];
    }
    return _availableMaps;
}

- (MAMapView *)mapView {
    if (!_mapView) {
        [MAMapServices sharedServices].apiKey = (NSString *)APIKey2;
        self.mapView = [[MAMapView alloc] initWithFrame:self.view.bounds];
        // 设置代理
        _mapView.delegate = self;
        // 罗盘位置
        _mapView.compassOrigin = CGPointMake(_mapView.compassOrigin.x, 70);
        // 比例尺位置
        _mapView.scaleOrigin = CGPointMake(_mapView.scaleOrigin.x, 70);
        
        // 4.开启定位
        _mapView.showsUserLocation = YES;
    }
    return _mapView;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:YES];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navigationBar"] forBarMetrics:UIBarMetricsDefault];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:YES];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navigation_bar_background"] forBarMetrics:UIBarMetricsDefault];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"导航" style:UIBarButtonItemStyleDone target:self action:@selector(daohangAction)];
    
    self.annotationArray = [NSMutableArray array];
    
    // 添加地图
    [self.view addSubview:self.mapView];
    _annotation = [[MAPointAnnotation alloc] init];
    _annotation.coordinate = CLLocationCoordinate2DMake([self.lat floatValue], [self.lng floatValue]);
    
    _annotation.title = self.name;
    _annotation.subtitle = self.address;
    // 设置缩放比
    self.mapView.zoomLevel = 16; // 最大20
    // 添加大头针
    //[self.annotationArray addObject:self.annotation];
    [self.mapView addAnnotation:self.annotation];
    // 地图上添加大头针
    //[self.mapView addAnnotations:self.annotationArray];
    self.mapView.centerCoordinate = _annotation.coordinate;
    // 将所有的大头针显示在地图上, 当数组中只有一个大头针的时候,会将大头针显示在地图中心
    //[self.mapView showAnnotations:self.mapView.annotations animated:YES];
}

#pragma mark - 获取当前位置 经纬度
/** 当位置更新时，会进定位回调，通过回调函数，能获取到定位点的经纬度坐标，*/
- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation {
    // 取出当前位置的坐标
    if (updatingLocation) {
        // 用户当前位置
        _currentLocation = [userLocation.location copy];
    }
    
}
#pragma mark - MAMapViewDelegate大头针 添加大头针调用这个方法
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
        MAPinAnnotationView *annotationView = (MAPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        if (annotationView == nil)
        {// 重用池(用法和tableViewcell一样,当在地图中不显示大头针时,就回收)
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
        }
        annotationView.canShowCallout= YES;       //设置气泡可以弹出，默认为NO
        annotationView.animatesDrop = YES;        //设置标注动画显示，默认为NO
        annotationView.draggable = YES;        //设置标注可以拖动，默认为NO
        annotationView.pinColor = MAPinAnnotationColorPurple;
        return annotationView;
    }
    return nil;
}

#pragma mark - 导航
- (void)daohangAction {
    
    [self availableMapsApps];
    UIActionSheet *action = [[UIActionSheet alloc] init];
    
    [action addButtonWithTitle:@"使用系统自带地图导航"];
    for (NSDictionary *dic in self.availableMaps) {
        [action addButtonWithTitle:[NSString stringWithFormat:@"使用%@导航", dic[@"name"]]];
    }
    [action addButtonWithTitle:@"取消"];
    action.cancelButtonIndex = self.availableMaps.count + 1;
    action.delegate = self;
    [action showInView:self.view];
    
}
- (void)availableMapsApps {
    [self.availableMaps removeAllObjects];
    
    CLLocationCoordinate2D startCoor = self.mapView.userLocation.location.coordinate;
    CLLocationCoordinate2D endCoor = CLLocationCoordinate2DMake([self.lat floatValue] + 0.01, [self.lng floatValue] + 0.01);
    NSString *toName = self.name;
    
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://map/"]]){
        NSString *urlString = [NSString stringWithFormat:@"baidumap://map/direction?origin=latlng:%f,%f|name:我的位置&destination=latlng:%f,%f|name:%@&mode=transit",
                               startCoor.latitude, startCoor.longitude, endCoor.latitude, endCoor.longitude, toName];
        NSDictionary *dic = @{@"name": @"百度地图",
                              @"url": urlString};
        [self.availableMaps addObject:dic];
        NSLog(@"--------------%@", self.availableMaps);
        
    }
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]) {
        NSString *urlString = [NSString stringWithFormat:@"iosamap://navi?sourceApplication=%@&backScheme=applicationScheme&poiname=fangheng&poiid=BGVIS&lat=%f&lon=%f&dev=0&style=3",
                               @"云华时代", endCoor.latitude, endCoor.longitude];
        
        NSDictionary *dic = @{@"name": @"高德地图",
                              @"url": urlString};
        [self.availableMaps addObject:dic];
        NSLog(@"--------------%@", self.availableMaps);
        
    }
    
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        CLLocationCoordinate2D startCoor = self.mapView.userLocation.location.coordinate;
        //CLLocationCoordinate2D endCoor = CLLocationCoordinate2DMake([self.lat floatValue] + 0.01, [self.lng floatValue] + 0.01);
        CLLocationCoordinate2D endCoor = CLLocationCoordinate2DMake(startCoor.latitude + 0.01, startCoor.longitude + 0.01);
        // 直接调用ios自己带的apple map
        MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
        //NSLog(@"======%@", currentLocation);
        MKPlacemark *placemark = [[MKPlacemark alloc] initWithCoordinate:endCoor addressDictionary:nil];
        MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:placemark];
        toLocation.name = self.name;
        
        [MKMapItem openMapsWithItems:@[currentLocation, toLocation]
                       launchOptions:@{MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving,MKLaunchOptionsShowsTrafficKey: [NSNumber numberWithBool:YES]}];
        
        
    }else if (buttonIndex < self.availableMaps.count + 1) {
        NSDictionary *mapDic = self.availableMaps[buttonIndex - 1];
        NSString *urlString = mapDic[@"url"];
        urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL *url = [NSURL URLWithString:urlString];
        NSLog(@"\n%@\n%@\n%@", mapDic[@"name"], mapDic[@"url"], urlString);
        [[UIApplication sharedApplication] openURL:url];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
